package com.sondon.dev_info.daoImpl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import com.sondon.dev_info.dao.DaoTemplate;

@Component("DaoTemplateImpl")
public class DaoTemplateImpl<T> implements DaoTemplate<T> {
	@Resource(name="sessionFactory")
	private SessionFactory sessionFactory;
	
	@SuppressWarnings("unchecked")
	@Override
	public T  get(String id,Class<T> t) {
		String hql="from "+t.getName()+" t where t.id=:id";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setString("id", id);
		return (T) query.uniqueResult();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public T get_by_hql(String hql) {
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		return (T) query.uniqueResult();
	}
	
	@Override
	public boolean update(T t) {
		try {
			sessionFactory.getCurrentSession().update(t);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}


	@SuppressWarnings("unchecked")
	@Override
	public List<T> getAll(Class<T> t) {
		String hql = "from "+t.getName();
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		return query.list();
	}

	@Override
	public void add(T t) {
		sessionFactory.getCurrentSession().save(t);
//		sessionFactory.getCurrentSession().flush();
	}

	@Override
	public boolean del(String id, Class<T> t) {
		String hql = "delete "+t.getName()+" t where t.id = :id";
		System.out.println("del hql  :"+hql);
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString("id", id);
		return (query.executeUpdate() > 0);
	}

	@Override
	public boolean save_update(T t) {
		try {
			sessionFactory.getCurrentSession().saveOrUpdate(t);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
